/**
 * WdAjax,封装jquery.ajax方法。
 * 内置submitToken,ajax缓存，success的统一处理，error的统一处理
 */
class WdAjax {
	constructor() {
		/** token 白名单*/
		this.submitTokenExclude = ['/login'];
		this.ajaxCacheFlag = false;
		this.ajaxOptions = {}
		this.server = 'http://10.133.232.35:9999'
		// this.server = 'http://11.205.243.83:9999'
		this.isTestData = true;
	}

	ajax(options = {}) {
		let self = this;
		this.ajaxOptions = {
			url: options.testUrl || options.url,
			type: options.type || "POST",
			data: options.type=='POST'?JSON.stringify(options.data):options.data,
			dataType: "json",
			contentType: options.contentType || "application/json",
			success: function (data, textStatus) {
				if(self.isTestData){
					if (data.code && data.code == 'O000000') {
						if (options.success) {
							options.success(data.result, self.isTestData);
						}
					} else {
						alertify.error(data.message, self.isTestData);
					}
				}else{
					if (data.code == '0') {
						if (options.success) {
							options.success(data.data, self.isTestData);
						}
					} else {
						options.error(data, self.isTestData);
						alertify.error(data.message, self.isTestData);
					}
				}

			},
			error: function (error) {
				if (options.error) {
					let flag = options.error(error);
					if (flag === false) {
						return false;
					}
				}
				alertify.error(JSON.stringify(error))
			},
			complete: function (XMLHttpRequest, textStatus) {
				if (options.complete) {
					options.complete(XMLHttpRequest, textStatus);
				}
			}
		};
		//-----------------------mock 数据 start
		if (false&&mock[this.ajaxOptions.url.replace(/^\//, '').replace(/\?.*/, '')]) {
			this.isTestData = true;
			options.success(mock[this.ajaxOptions.url.replace(/^\//, '').replace(/\?.*/, '')].result, this.isTestData);
			return false;
		} else {
			this.isTestData = false;
			this.ajaxOptions.url = (this.server + this.ajaxOptions.url).replace(/\d\/\//,(str)=>{
				return str.replace('//','');
			});
		}
		//-----------------------mock 数据 end
		$.ajax(this.ajaxOptions);
	}

	/**
	 * wdAjax.get  GET方式获取数据
	 * @param {Object} options 
	 */
	get(options = {}) {
		options.type = 'GET'
		this.ajax(options)
	}
	/**
	 * wdAjax.post  POST方式获取数据
	 * @param {Object} options 
	 */
	post(options = {}) {
		options.type = 'POST'
		this.ajax(options)
	}
}
let wdAjax = new WdAjax();